package znet

import (
	"bytes"
	"encoding/binary"
	"errors"
	"zinx/utils"
	"zinx/ziface"
)

type DataPack struct {
	//HeadLen uint32
}

func (dp *DataPack) GetHeadLen() uint32 {
	/// msgId 和 dataLen的长度
	return 8
}

func (dp *DataPack) Pack(msg ziface.IMessage) ([]byte, error) {
	/// 创建一个writeBuf
	dataBuf := bytes.NewBuffer([]byte{})

	/// 写入数据长度
	if err := binary.Write(dataBuf, binary.LittleEndian, msg.GetMsgLength()); err != nil {
		return nil, err
	}

	/// 写入msgId
	if err := binary.Write(dataBuf, binary.LittleEndian, msg.GetMsgId()); err != nil {
		return nil, err
	}

	/// 写入数据
	if err := binary.Write(dataBuf, binary.LittleEndian, msg.GetMsgLength()); err != nil {
		return nil, err
	}

	return dataBuf.Bytes(), nil
}

func (dp *DataPack) UnPack(data []byte) (ziface.IMessage, error) {
	/// 创建读取readerbuf
	readBuf := bytes.NewBuffer(data)

	/// 创建空的msg
	msg := &Message{}

	/// 读取包头长度
	if err := binary.Read(readBuf, binary.LittleEndian, &msg.MsgLength); err != nil {
		return nil, err
	}

	/// 读取数据长度
	if err := binary.Read(readBuf, binary.LittleEndian, &msg.MsgId); err != nil {
		return nil, err
	}

	if utils.GlobalObject.MaxPackageSize > 0 && msg.MsgLength > utils.GlobalObject.MaxPackageSize {
		return nil, errors.New("too large msg data receved!")
	}
	/// 返回msg
	return msg, nil
}
